<template>
  <view class="page">
    <mineNavbar :styleData="styleData" />

    <scroll-view class="scroll" scroll-y>
      <view class="form">
        <view class="form-item-title">
          <view class="title">
            <view class="text">企业资料</view>
            <view class="borderB"> </view>
          </view>
        </view>

        <view class="form-item">
          <view class="item-inner">
            <view class="label"> 公司名称 </view>
            <input class="input" v-model="form.fullName" type="text" placeholder="请填写" />
          </view>
          <view class="line" />
        </view>
        <view class="form-item">
          <view class="item-inner">
            <view class="label"> 公司简称 </view>
            <input class="input" v-model="form.abbreviationName" type="text" placeholder="请填写" />
          </view>
          <view class="line" />
        </view>

        <!-- 公司规模 -->
        <view class="form-item">
          <view class="item-inner">
            <view class="label"> 公司规模 </view>
            <picker style="flex: 1" @change="scaleChange" :value="scaleIndex" :range="scaleList">
              <view class="content-box">
                <view class="textData"> {{ labelForm.scale }} </view>

                <view class="arrows">
                  <image src="@/static/images/emterpriseMineImg/arrow-right.png" />
                </view>
              </view>
            </picker>
          </view>
          <view class="line" />
        </view>
        <!-- 公司类型 -->
        <view class="form-item">
          <view class="item-inner">
            <view class="label"> 公司类型 </view>
            <picker v-model="form.enterpriseNature" style="flex: 1" @change="natureChange" :value="natureIndex"
              :range="natureList">
              <view class="content-box">
                <view class="textData">
                  {{ labelForm.type }}
                </view>
                <view class="arrows">
                  <image src="@/static/images/emterpriseMineImg/arrow-right.png" />
                </view>
              </view>
            </picker>
          </view>

          <view class="line" />
        </view>

        <!-- 所属行业 -->
        <view class="form-item">
          <view class="item-inner">
            <view class="label"> 所属行业 </view>
            <picker v-model="industryIndex" :range="industryList" @change="changeIndustryId" range-key="label">
              <!-- 描述+icon -->
              <view class="content-box1">
                <view class="textData">
                  {{ labelForm.industry }}
                </view>

                <view class="arrows">
                  <image src="@/static/images/emterpriseMineImg/arrow-right.png" />
                </view>
              </view>
            </picker>
          </view>

          <view class="line" />
        </view>

        <!-- 所在地区 -->
        <view class="form-item" @click="regionOpen">
          <view class="item-inner">
            <view class="label"> 所在地区 </view>
            <view class="content-box1">
              <view class="textData">
                {{ regionText || '请选择所在地区' }}
              </view>

              <view class="arrows">
                <image src="@/static/images/emterpriseMineImg/arrow-right.png" />
              </view>
            </view>
            <!-- <uni-data-picker v-model="address" style="flex: 1" popup-title="所在地区" :map="{ text: 'label', value: 'id' }"
              :border="false" :clear-icon="false" :localdata="addressTree" :preload="true" @change="addressTreeChange">
              <view class="content-box">
                <view class="textData">
                  {{ labelForm.address }}
                </view>

                <view class="arrows">
                  <image src="@/static/images/emterpriseMineImg/arrow-right.png" />
                </view>
              </view>
            </uni-data-picker> -->
          </view>

          <view class="line" />
        </view>

        <!-- 公司地址 -->
        <view class="form-item">
          <view class="item-inner">
            <view class="label"> 公司地址 </view>
            <input class="input" v-model="form.detailedAddress" type="text" placeholder="请填写" />
          </view>
          <view class="line" />
        </view>
      </view>

      <!-- 其他信息 -->
      <view class="form-1">
        <view class="form-item-title">
          <view class="title">
            <view class="text">其他信息</view>
            <view class="borderB"> </view>
          </view>
        </view>

        <view class="form-item">
          <view class="item-inner">
            <view class="label" style="margin-right: 68rpx"> 联系人 </view>
            <input class="input" v-model="form.contactName" type="text" placeholder="请填写" />
          </view>
          <view class="line" />
        </view>

        <view class="form-item">
          <view class="item-inner">
            <view class="label"> 联系电话 </view>
            <input class="input" v-model="form.contactPhone" type="text" placeholder="请填写" maxlength="11" />
          </view>
          <view class="line" />
        </view>

        <view class="form-item-logo">
          <view class="item-inner" style="margin-top: 20rpx">
            <view class="label"> 公司logo </view>
            <upload-img @change="uploadImgFn" :limit="1" title="支持上传jpg/png" :value="fileList">
              <image style="width: 100%; height: 100%; flex-shrink: 0"
                src="http://wangxinbao.oss-cn-beijing.aliyuncs.com/2024/04/18/514bd029aaa046e3a4749a6191d54ebd.png"
                mode="aspectFit|aspectFill|widthFix" lazy-load="false" binderror="" bindload="" />
            </upload-img>
          </view>
        </view>
      </view>

      <view class="submit" @click="submitFn"> 保存 </view>
      <view style="height: 200rpx" />
    </scroll-view>
    <region-select ref="regionSelect" :showLevel="3" @change="regionChange"></region-select>
  </view>
</template>

<script>
import uploadImg from "@/components/uploadImg/uploadImg";
import { getEntInfo, saveEnterprise } from "@/api/subPage/mine.js";
import regionSelect from "@/components/selectPopup/regionSelect";
import { verifyMobile } from '@/utils/toast'

import {
  industryTree,
  getDictType,
  selectLabel,
  regionList,
  regionTreeLevel,
  regionTreeAPI,
} from "@/api/common.js";
export default {
  components: { uploadImg, regionSelect },
  data() {
    return {
      styleData: {
        tabbarText: "企业资料",
        show: true,
      },

      // 表单提交
      form: {
        enterpriseId: undefined, // 企业编号
        fullName: "", // 全称
        abbreviationName: "", //简称
        enterpriseNature: "", // 企业性质（使用数据字典：企业性质，“wxb_enterprise_nature”）
        enterpriseScale: "", // 企业规模（使用数据字典：企业规模，“wxb_enterprise_scale“）
        industrySector: "", // 所属行业 （通过通用接口：获取行业分类树列表获取行业id）
        province: "", // 省
        city: "", // 市
        area: "", // 区
        detailedAddress: "", // 详细地址
        contactName: "", // 联系人姓名
        contactPhone: "", // 联系电话
        url: "", // 企业logo
      },

      // 行业选择列表
      industryList: [],
      industryIndex: '', // 行业选中的下标

      // 企业规模
      scaleDict: [],
      // 值
      scaleList: [],
      scaleIndex: undefined,

      // 企业性质
      natureDict: [],
      natureList: [],
      natureIndex: undefined,

      // 地区
      address: [],
      addressTree: [],

      fileList: [],

      // labelForm
      labelForm: {
        // 规模
        scale: "请选择公司规模",
        type: "请选择公司类型",
        industry: "请选择所属行业",
        address: "请选择所在地址",
      },

      regionText: "", // 省市区
    };
  },
  computed: {},
  // 监控data中的数据变化
  watch: {},
  onLoad(options) {
    this.getSelectFn();
    this.getDetail();
  },
  onShow() {
  },
  mounted() {
    this.getSelectFn();
    console.log(this.industryList);
    this.getDetail();
  },
  onReady() { },
  methods: {
    // 省市区弹框
    regionOpen() {
      this.$refs.regionSelect.popupOpen();
    },
    regionChange(data) {
      console.log(data);
      // this.regionText = data
      this.form.province = data[0].id; // 省
      this.form.city = data[1].id; // 市
      this.form.area = data[2].id; // 区
      // this.form.street = data[3].id; //街道
      this.regionText = data.reduce((pre, item) => {
        let line = pre == "" ? "" : "/";
        return pre + line + item.name;
      }, "");
    },
    // 保存
    submitFn() {
      let timer = null;
      clearTimeout(timer);
      console.log(this.form.contactPhone);
      if (verifyMobile(this.form.contactPhone)) {
        saveEnterprise(this.form).then((res) => {
          console.log(res);
          if (res.code === 200) {
            uni.showToast({
              title: "保存成功",
              icon: "success",
              duration: 2000,
            });
            timer = setTimeout(() => {
              uni.navigateBack();
            }, 1500);
            this.$store.commit('SET_entDataStatus', '1')
          }
        });
      }
    },

    // 递归获取所属行业
    findItemById(dataList, targetId) {
      for (const item of dataList) {
        if (item.id === targetId) {
          return item;
        }

        if (item.children && Array.isArray(item.children)) {
          const foundInChildren = this.findItemById(item.children, targetId);

          if (foundInChildren) {
            return foundInChildren;
          }
        }
      }
      return null;
    },

    // 获取详情
    getDetail() {
      getEntInfo().then((res) => {
        let data = res.data;

        data.address = "123"; // 后端无用字段
        console.log(!Object.values(data).includes(""));

        this.regionText = `${data.provinceLabel}/${data.cityLabel}/${data.areaLabel}`

        // if (!Object.values(data).includes("")) {

        //   this.form = Object.assign({}, this.form, data);

        //   this.fileList = [data.url];

        //   this.scaleIndex = this.scaleDict.findIndex(
        //     (v) => v.dictValue === data.enterpriseScale
        //   );

        //   this.natureIndex = this.natureDict.findIndex(
        //     (v) => v.dictValue === data.enterpriseNature
        //   );

        //   // 公司规模label
        //   this.labelForm.scale = this.scaleList[this.scaleIndex];
        //   // 企业性质label
        //   this.labelForm.type = this.natureList[this.natureIndex];
        //   // 所属行业label
        //   const foundItem = this.findItemById(
        //     this.industryList,
        //     data.industrySector
        //   );
        //   this.labelForm.industry = foundItem.label;

        //   // 省市区label
        //   this.labelForm.address =
        //     data.provinceLabel + "/" + data.cityLabel + "/" + data.areaLabel;
        // } else {
        //   this.form = {
        //     enterpriseId: undefined, // 企业编号
        //     fullName: "", // 全称
        //     abbreviationName: "", //简称
        //     enterpriseNature: "", // 企业性质（使用数据字典：企业性质，“wxb_enterprise_nature”）
        //     enterpriseScale: "", // 企业规模（使用数据字典：企业规模，“wxb_enterprise_scale“）
        //     industrySector: "", // 所属行业 （通过通用接口：获取行业分类树列表获取行业id）
        //     province: "", // 省
        //     city: "", // 市
        //     area: "", // 区
        //     detailedAddress: "", // 详细地址
        //     contactName: "", // 联系人姓名
        //     contactPhone: "", // 联系电话
        //     url: "", // 企业logo
        //   };
        // }

        this.form = Object.assign({}, this.form, data);

        this.fileList = data.url ? [data.url] : [];

        // 公司规模label
        if (data.enterpriseScale !== null) {
          this.scaleIndex = this.scaleDict.findIndex(
            (v) => v.dictValue === data.enterpriseScale
          );

          this.labelForm.scale = this.scaleList[this.scaleIndex];
        }

        // 企业性质label
        if (data.enterpriseNature !== null) {
          this.natureIndex = this.natureDict.findIndex(
            (v) => v.dictValue === data.enterpriseNature
          );
          this.labelForm.type = this.natureList[this.natureIndex];
        }

        // 所属行业label
        if (data.industrySector !== null) {
          const foundItem = this.findItemById(
            this.industryList,
            data.industrySector
          );
          this.labelForm.industry = foundItem.label || "";
          this.industryList.forEach((element, index) => {
            if (element.id === data.industrySector) {
              this.industryIndex = index
            }
          });
        }

        // 省市区label
        if (
          data.provinceLabel !== null &&
          data.provinceLabel !== "" &&
          data.cityLabe !== null &&
          data.cityLabe !== "" &&
          data.areaLabel !== null &&
          data.areaLabel !== ""
        ) {
          this.labelForm.address =
            data.provinceLabel + "/" + data.cityLabel + "/" + data.areaLabel;
        }
      });
    },

    getSelectFn() {
      // 所属行业
      industryTree().then((res) => {
        // console.log(res.data)
        this.industryList = res.data;
      });
      // 企业规模
      getDictType("wxb_enterprise_scale").then((res) => {
        this.scaleDict = res.data;
        this.scaleList = res.data.map((v) => v.dictLabel);
      });
      // 企业性质
      getDictType("wxb_enterprise_nature").then((res) => {
        this.natureDict = res.data;
        this.natureList = res.data.map((v) => v.dictLabel);
      });

      // 获取省市结构 二级
      regionTreeAPI().then((res) => {
        this.addressTree = res.data;
      });
    },
    // 监听地址
    addressTreeChange(e) {
      console.log(e.detail.value, "---------9");

      let arr = e.detail.value;
      this.form.province = arr[0].value;
      this.form.city = arr[1].value;
      this.form.area = arr[2].value;
      this.labelForm.address = arr.map((item) => item.text).join("/");
    },

    // 监听企业规模
    scaleChange(e) {
      let index = e.detail.value;
      this.scaleIndex = index;
      this.form.enterpriseScale = this.scaleDict[index].dictValue;
      // 规模值
      this.labelForm.scale = this.scaleList[index];
    },
    // 监听企业性质
    natureChange(e) {
      let index = e.detail.value;
      this.natureIndex = index;
      this.form.enterpriseNature = this.natureDict[index].dictValue;
      this.labelForm.type = this.natureList[index];
    },
    // 监听所属行业
    changeIndustryId(e) {
      const arr = e.detail.value;
      // this.labelForm.industry = arr.map((item) => item.text).join("/");
      this.labelForm.industry = this.industryList[e.detail.value].label
      this.form.industrySector = this.industryList[e.detail.value].id
    },
    // 上传图片监听
    uploadImgFn(data) {
      if (data && Array.isArray(data)) {
        this.fileList = data.map((v) => v.url);
        this.form.url = data[0].url;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  height: 100vh;
  overflow: hidden;

  background-color: #f9f9f9;

  ::v-deep .placeholder {
    font-weight: 500;
    font-size: 28rpx;
    color: #000000e0;
  }

  .scroll {
    display: flex;
    position: relative;
    width: 700rpx;
    height: 100%;
    overflow: hidden;
    margin: 0 24rpx;
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;

    // 头部表单
    .form {
      margin-top: 24rpx;
      width: 100%;
      padding-bottom: 33rpx;
      border-radius: 16rpx;
      background-color: #fff;
      display: flex;
      flex-direction: column;
      align-items: center;

      .form-item-title {
        width: 100%;
        margin-top: 28rpx;

        .title {
          position: relative;
          width: 128rpx;
          height: 45rpx;
          font-weight: 500;
          font-size: 32rpx;
          color: #000000e0;
          margin-left: 24rpx;
          margin-bottom: 24rpx;

          .text {
            z-index: 99;
            position: absolute;
          }

          .borderB {
            position: absolute;
            bottom: 4rpx;
            width: 50%;
            height: 14rpx;
            background-color: #ff9e24;
            z-index: 10;
            border-radius: 10rpx;
          }
        }
      }

      // 头部表单
      .form-item {
        position: relative;
        height: 98rpx;
        width: 702rpx;
        display: flex;
        flex-direction: column;
        justify-content: center;

        .item-inner {
          display: flex;
          align-items: center;
          margin-left: 24rpx;
          width: 100%;
          height: 100%;

          .label {
            font-weight: 500;
            font-size: 28rpx;
            color: #000000;
            opacity: 0.45;
            margin-right: 40rpx;
          }

          .content-box {
            display: flex;
            align-items: center;
            width: 90%;
            justify-content: space-between;

            .textData {
              font-weight: 500;
              font-size: 28rpx;
              color: #000000e0;
            }

            //图片
            .arrows {
              width: 26rpx;
              height: 26rpx;

              image {
                width: 100%;
                height: 100%;
              }
            }
          }

          .content-box1 {
            display: flex;
            align-items: center;
            width: 500rpx;
            justify-content: space-between;

            .textData {
              font-weight: 500;
              font-size: 28rpx;
              color: #000000e0;
            }

            //图片
            .arrows {
              width: 26rpx;
              height: 26rpx;

              image {
                width: 100%;
                height: 100%;
              }
            }
          }
        }

        .line {
          height: 2rpx;
          background-color: #f2f2f2;
          margin: 0 24rpx;
        }
      }
    }

    .form-1 {
      margin-top: 24rpx;
      width: 100%;
      padding-bottom: 33rpx;
      border-radius: 16rpx;
      background-color: #fff;
      display: flex;
      flex-direction: column;
      align-items: center;

      .form-item-title {
        width: 100%;
        margin-top: 28rpx;

        .title {
          position: relative;
          width: 128rpx;
          height: 45rpx;
          font-weight: 500;
          font-size: 32rpx;
          color: #000000e0;
          margin-left: 24rpx;
          margin-bottom: 24rpx;

          .text {
            z-index: 99;
            position: absolute;
          }

          .borderB {
            position: absolute;
            bottom: 4rpx;
            width: 50%;
            height: 14rpx;
            background-color: #ff9e24;
            z-index: 10;
            border-radius: 10rpx;
          }
        }
      }

      .form-item {
        position: relative;
        height: 98rpx;
        width: 702rpx;
        display: flex;
        flex-direction: column;
        justify-content: center;

        .item-inner {
          display: flex;
          align-items: center;
          margin-left: 24rpx;
          margin-right: 24rpx;

          height: 100%;

          .label {
            font-weight: 500;
            font-size: 28rpx;
            color: #000000;
            opacity: 0.45;
            margin-right: 40rpx;
          }

          .desc {
            font-weight: 500;
            font-size: 28rpx;
            color: #000000e0;
          }

          .arrows {
            display: flex;
            align-items: center;

            width: 26rpx;
            height: 26rpx;

            image {
              width: 100%;
              height: 100%;
            }
          }
        }

        .line {
          height: 2rpx;
          background-color: #f2f2f2;
          margin: 0 24rpx;
        }
      }

      .form-item-logo {
        position: relative;

        width: 702rpx;
        display: flex;
        flex-direction: column;
        justify-content: center;

        .item-inner {
          display: flex;
          flex-direction: column;
          justify-content: center;
          margin-left: 24rpx;
          margin-right: 24rpx;

          height: 100%;

          .label {
            font-weight: 500;
            font-size: 28rpx;
            color: #000000;

            margin-right: 40rpx;
          }

          .support {
            font-weight: 500;
            font-size: 22rpx;
            color: #00000073;
            letter-spacing: 0;
            margin-bottom: 20rpx;
          }
        }
      }
    }

    .submit {
      width: 420rpx;

      margin: 80rpx auto;
      background: #ff9e24;
      border-radius: 44rpx;
      line-height: 88rpx;
      font-weight: 500;
      font-size: 32rpx;
      color: #ffffff;
      text-align: center;
    }
  }
}
</style>
